<?php

class Materials_Helper_Application extends Workset_Controller_Action_Helper_Application {

    protected $_maxImageWidth = 1024;

    function getCategory($id, $req = false) {
        $request = $this->getRequest();

		if (true == $req) {
			$id = (int)$request->getParam((string)$id);
		} else {
			$id = (int)$id;
		}

		if ($id < 1) {
            throw $this->throwException(null, 404);
        }

        $category = Materials_Model_Category::getInstance($id);

        if (!$category) {
            throw $this->throwException(null, 404);
        }

		return $category;
	}

    function getMaterial($id, $req = false) {
        $request = $this->getRequest();

		if (true == $req) {
			$id = (int)$request->getParam((string)$id);
		} else {
			$id = (int)$id;
		}

		if ($id < 1) {
            throw $this->throwException(null, 404);
        }

        $material = Materials_Model_Material::getInstance($id);

        if (!$material) {
            throw $this->throwException(null, 404);
        }

		return $material;
    }

    function getLabel($id, $req = false) {
        $request = $this->getRequest();

		if (true == $req) {
			$id = (int)$request->getParam((string)$id);
		} else {
			$id = (int)$id;
		}

		if ($id < 1) {
            throw $this->throwException(null, 404);
        }

        $label = Materials_Model_Label::getInstance($id);

        if (!$label) {
            throw $this->throwException(null, 404);
        }

		return $label;
    }

    function getPostContent($options, $post, $files = array()) {
        $result = array();

        $contentOrder = isset($post['order']) ? $post['order'] : array();

        $count = 1;

        foreach ($options as $block) {

            $name = $block['name'];

            if (isset($post[$name])) {

                $block['hidden'] = false;
                
                if (empty($block['multiple'])) {

                    foreach ($block['items'] as $key => $item) {
                        $itemName = $item['name'];

                        //строковое значение
                        if (isset($post[$name][$itemName])) {
                            $block['items'][$key]['value'] = $post[$name][$itemName];

                        }
                        //загруженный файл
                        elseif (in_array($item['type'], Materials_Model_Material::getFileTypes()) && $files) {
                            if (isset($files[$name][$itemName])) {
                                $file = $files[$name][$itemName];

                                if ($file instanceof Workset_File_Info) {

                                   $file = $file->toArray(array('name', 'shortpath', 'size', 'ctime', 'mimetype'));

                                } elseif (!is_array($file)) {
                                    continue;
                                }

                                $block['items'][$key]['value'] = $file;
                            }
                        }
                    }

                    if (isset($contentOrder[$name][0])) {
                        $pos = (int)$contentOrder[$name][0];
                        $result[$pos] = $block;
                    } 
                    /*else {
                        $result[] = $block;
                    }*/

                } else {

                    foreach ($post[$name] as $key => $items) {

                        $itemBlock = $block;

                        $itemBlock['index'] = $count++;

                        foreach ($itemBlock['items'] as $index => $item) {
                            $itemName = $item['name'];

                            //строковое значение
                            if (isset($post[$name][$key][$itemName])) {
                                $itemBlock['items'][$index]['value'] = $post[$name][$key][$itemName];
                            }
                            //загруженный файл
                            elseif (in_array($item['type'], Materials_Model_Material::getFileTypes()) && $files) {
                                if (isset($files[$name][$key][$itemName])) {
                                    $file = $files[$name][$key][$itemName];

                                    if ($file instanceof Workset_File_Info) {

                                       $file = $file->toArray(array('name', 'shortpath', 'size', 'ctime', 'mimetype'));

                                    } elseif (!is_array($file)) {
                                        continue;
                                    }
                                    
                                    $itemBlock['items'][$index]['value'] = $file;
                                }

                            }
                        }

                        if (isset($contentOrder[$name][$key])) {
                            $pos = (int)$contentOrder[$name][$key];
                            $result[$pos] = $itemBlock;
                        } else {
                            $result[] = $itemBlock;
                        }
                    }
                }

                unset($post[$name]);
            }
        }

		ksort($result);

        return $result;
    }

    function getUploadedFiles($options, $fileinfo) {
        $names = array();
        $result = array();

        foreach ($options as $block) {
            $names[] = $block['name'];
        }

        foreach ($fileinfo as $key => $file) {

            if ($file instanceof Workset_File_Info_Image && null !== $this->_maxImageWidth) {
                $file->getHandler()->resizeBySide('width', $this->_maxImageWidth)->save();
            }

            foreach ($names as $name) {
                if (0 === strpos($key, $name)) {

                    $index = null;
                    $parts = explode('_', substr($key, strlen($name)));
                    $parts = array_filter($parts);
                    $key = array();

                    $index = array_shift($parts);
                    if (!isInt($index)) {
                        $key[] = $index;
                        $index = null;
                    }

                    $key = implode('_', array_merge($key, $parts));

                    if (null !== $index) {
                        $result[$name][$index][$key] = $file;
                    } else {
                        $result[$name][$key] = $file;
                    }

                    break;

                }
            }
        }

        return $result;
    }

    function getContentOptions(array $options, $values = null) {
        $result = array();
        $pos = 0;

        foreach ($options as $key => $spec) {

            //обработка группы полей
            if (!empty($spec['elements'])) {

                $result[] = array(
                    'name'  => $spec['type'],
                    'index' => $pos++,
                    'legend' => $spec['legend'],
                    'hidden' => !empty($spec['hidden']),
                    'multiple' => !empty($spec['multiple']),

                    //список полей блока
                    'items' => $this->getContentOptions($spec['elements'])
                );
			}

            //обработка поля
            if (!empty($spec['fields'])) {

                $result[] = array(
                    'name'  => $spec['fields']['name'],
                    'type'  => $spec['fields']['type'],
                    'label' => $spec['fields']['label'],
                    'value' => $spec['fields']['value'],
                    'attrs' => array(
                        'class' => isset($spec['options']['class']) ? $spec['options']['class'] : ''
                    )
                );
            }
        }

        return $result;
    }

}